package com.study.c4;

import java.util.StringJoiner;

public class ArrayToString
{
    // 在一行打印数组
    public static void printArr(int[] arr)
    {
        System.out.print("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                System.out.println(arr[i] + "]");
            } else {
                System.out.print(arr[i] + ", ");
            }
        }
    }

    // 数组元素拼接成字符串
    public static String arrToString(int[] arr)
    {
        String s = "";
        s = s + "[";
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                s = s + arr[i];
            } else {
                //noinspection StringConcatenationInLoop
                s += arr[i] + ", ";
            }
        }
        s = s + "]";
        return s;
    }

    // StringBuilder 拼接数组
    public static String arrToString1(int[] arr)
    {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(", ");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    // StringJoiner 拼接数组
    public static String arrToString2(int[] arr)
    {
        StringJoiner sj = new StringJoiner(", ", "[", "]");
        for (int e : arr) {
            sj.add(String.valueOf(e));
        }
        return sj.toString();
    }
}
